package com.example.day1.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.day1.DTO.SetmealDto;
import com.example.day1.common.CustomException;
import com.example.day1.entity.Setmeal;
import com.example.day1.entity.SetmealDish;
import com.example.day1.mapper.SetmealMapper;
import com.example.day1.service.SetmealDishService;
import com.example.day1.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    //关系表
    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto){
        //保存信息
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

    };

    @Override
    public void removeWithDish(List<Long> ids) throws CustomException {
        LambdaQueryWrapper<Setmeal> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();

        objectLambdaQueryWrapper.in(Setmeal::getId,ids);
        objectLambdaQueryWrapper.eq(Setmeal::getStatus,1);
        if(setmealService.count(objectLambdaQueryWrapper)>0){
            throw new CustomException("订单处于售卖状态，不能删除");
        }
        setmealService.removeByIds(ids);
        ///删除口味
        LambdaQueryWrapper<SetmealDish> objectLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper2.in(SetmealDish::getSetmealId,ids);
       setmealDishService.remove(objectLambdaQueryWrapper2);
    }
}
